//
//  DiDiVPNStore.m
//  KDExample
//
//  Created by YeQing on 2017/3/23.
//  Copyright © 2017年 naruto. All rights reserved.
//

#import "DiDiVPNStore.h"
#import "DiDiVPNHelper.h"
#import "DiDiVPNDefines.h"



@interface DiDiVPNStore()
@property (nonatomic, strong) NEVPNManager              *ddVPNManager;
@end


@implementation DiDiVPNStore
{
    
    NSString                        *_ddVPNServer;//vpn server 地址
}
#pragma mark - system
- (instancetype)init
{
    self = [super init];
    if (self) {
        _ddVPNServer = @"didivpn.didichuxing.com";//这里是 vpn server 地址
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNotifVPNStatusDidChange:) name:NEVPNStatusDidChangeNotification object:nil];
    }
    return self;
}
-(void)dealloc
{
    _delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NEVPNStatusDidChangeNotification object:nil];
}
#pragma mark - 连接vpn
- (void)startVPN
{
    __weak typeof(self) weakSelf = self;
    [DiDiVPNHelper loadDDVPNManager:^(NEVPNManager *vpnManager) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(!strongSelf){
            return ;
        }
        if(vpnManager){
            //存在 vpn，先去更新vpn配置
            strongSelf.ddVPNManager = vpnManager;
            [self updateDDVPN:^(NEVPNManager *vpnManager) {
                [self startDDVPN];
            }];
            
        }
        else{
            //不存在 vpn,先创建保存到系统里
            __weak typeof(self) weakSelf = self;
            [self createDDVPN:^(NEVPNManager *vpnManager) {
                __strong typeof(weakSelf) strongSelf = weakSelf;
                if(!strongSelf){
                    return ;
                }
                strongSelf.ddVPNManager = vpnManager;
                [vpnManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
                    [strongSelf startDDVPN];
                }];
            }];
        }
    }];
}

#pragma mark - 断开vpn
- (void)stopVPN
{
    DiDiVPNLogInfo(@"connection:%@",self.ddVPNManager.connection);
    [DiDiVPNHelper loadDDVPNManager:^(NEVPNManager *vpnManager) {
        [vpnManager.connection stopVPNTunnel];
    }];
}
#pragma mark - vpn 状态
-(DiDiVPNStatus)vpnStatus
{
    NEVPNConnection *vpnConnect = [self.ddVPNManager connection];
    return (DiDiVPNStatus)vpnConnect.status;
}

#pragma mark - private

/**
 创建VPN 配置
 
 @param complate 创建完成回调
 */
- (void)createDDVPN:(void(^)(NEVPNManager *vpnManager) )complate
{
    NETunnelProviderManager *vpnManager = [[NETunnelProviderManager alloc] init];
    NETunnelProviderProtocol *protocol = [[NETunnelProviderProtocol alloc] init];
    [protocol setServerAddress:_ddVPNServer];
    //            NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    //            NSData *data = [[NSData alloc] init];
    //            [dictionary setObject:@"UUID" forKey:(id)kSecAttrService];
    //            [dictionary setObject:data forKey:(id)kSecValueData];
    //            [dictionary setObject:(__bridge id)kSecAttrAccessibleAlways forKey:(id)kSecAttrAccessible];
    //            [dictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(id)kSecClass];
    //            [dictionary setObject:(__bridge id)kCFBooleanTrue forKey:(id)kSecReturnPersistentRef];
    //
    //            CFTypeRef passwordRef = nil;
    //
    //            OSStatus delStatus = SecItemDelete((__bridge CFDictionaryRef)dictionary);
    //            OSStatus status = SecItemAdd((__bridge CFDictionaryRef)dictionary, &passwordRef);
    
    //        [protocol setPasswordReference:(__bridge NSData * _Nullable)(passwordRef)];
    
    //    if(self.userName.length>0){
    //        [protocol setUsername:self.userName];
    //    }
    //    [self createKeychainValue:@"Ddcx@258012222" forIdentifier:@"VPN_PASSWORD"];
    //    protocol.passwordReference = [self searchKeychainCopyMatching:@"VPN_PASSWORD"];
    vpnManager.protocolConfiguration = protocol;
    vpnManager.localizedDescription = kDiDiVPN_LocalizedDescription;
    vpnManager.onDemandEnabled = YES;
    vpnManager.enabled = true;
    [vpnManager saveToPreferencesWithCompletionHandler:^(NSError *err) {
        DiDiVPNLog(@"DDVPN createVPN error:%@,connection:%@", err,vpnManager.connection);
        if(complate){
            complate(vpnManager);
        }
    }];
}


/**
 更新滴滴 vpn 参数
 
 @param complate 更新完成的回调
 */
-(void)updateDDVPN:(void(^)(NEVPNManager *vpnManager))complate
{
    //检测dd vpn enable
    if(!self.ddVPNManager){
        return;
    }
    BOOL needUpdate = NO;
    if(!self.ddVPNManager.isEnabled){
        DiDiVPNLog(@"DDVPN updatevpn enabled");
        needUpdate = YES;
        [self.ddVPNManager setEnabled:YES];
    }
    if(_ddVPNServer.length>0 && ![self.ddVPNManager.protocolConfiguration.serverAddress isEqualToString:_ddVPNServer]){
        DiDiVPNLog(@"DDVPN updatevpn server");
        needUpdate = YES;
        [self.ddVPNManager.protocolConfiguration setServerAddress:_ddVPNServer];
    }
    //判断是否需要更新
    if(needUpdate){
        [self.ddVPNManager saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
            DiDiVPNLog(@"DDVPN updatevpn error:%@", error);
            if(complate){
                complate(self.ddVPNManager);
            }
        }];
    }
    else{
        if(complate){
            complate(self.ddVPNManager);
        }
    }
}


/**
 开始启动 vpn
 */
-(void)startDDVPN
{
    if(!self.ddVPNManager){
        DiDiVPNLogInfo(@"vpn manager is nil");
        return;
    }
    NEVPNConnection *vpnConnect = [self.ddVPNManager connection];
    if( (vpnConnect.status==NEVPNStatusDisconnected) || (vpnConnect.status==NEVPNStatusInvalid) ){
        NSError *connError;
        //构造 vpn启动参数[NEVPNConnectionStartOptionUsername、NEVPNConnectionStartOptionPassword]
        NSMutableDictionary *dictParams = [[NSMutableDictionary alloc] initWithCapacity:2];
        if(self.userName.length>0){
            dictParams[NEVPNConnectionStartOptionUsername] = self.userName;
        }
        if(self.userPwd.length>0){
            dictParams[NEVPNConnectionStartOptionPassword] = self.userPwd;
        }
        //启动vpn
        BOOL startRes =  [vpnConnect startVPNTunnelWithOptions:dictParams andReturnError:&connError];
        DiDiVPNLogInfo(@"res:%d,error:%@", startRes, connError);
    }
}



#pragma mark - notifcation

-(void)onNotifVPNStatusDidChange:(NSNotification *)notif
{
    DiDiVPNStatus vpnStatus = [self vpnStatus];
    DiDiVPNLogInfo(@"status change:%ld", (long)vpnStatus);
    //通知使用者
    if([self.delegate respondsToSelector:@selector(onDiDiVPNStore:vpnStatusChange:)]){
        [self.delegate onDiDiVPNStore:self vpnStatusChange:vpnStatus];
    }
    
}

@end
